package com.appspot.showup_app.showup;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.TextWatcher;
import android.text.format.Time;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

import com.appspot.showup_app.showup.model.ShowUpAppointmentMessage;
import com.appspot.showup_app.showup.model.ShowUpCustomerMessage;
import com.appspot.showup_app.showup.tasks.UpdateAppointmentTask;
import com.google.api.client.util.DateTime;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.SimpleTimeZone;
import java.util.Timer;

/**
 * Created by Gal on 12/5/2014.
 */
public class AddEditAppointmentActivity extends ActionBarActivity {
    private static final String LOG_TAG = "AddEditAppointmentActivity";
    private static final String TAG = "Showup";

    final CharSequence[] items = {
            "No repeat", "Every day", "Every week", "Every month"
    };


    ShowUpAppointmentMessage appointment;
    AutoCompleteTextView editCustomer;
    EditText editTime;
    EditText editDate;
    EditText editDuration;
    EditText editNotes;
    EditText editRepeat;
    SQLiteDatabase db;
    ShowUpCustomerMessage selectedCustomer;

    int selectedDateYear;
    int selectedDateMonth;
    int selectedDateDay;
    int selectedTimeHour;
    int selectedTimeMin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_edit_appointment);

        if (!ApplicationData.getInstance().isLoggedIn())
        {
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }

        editCustomer = (AutoCompleteTextView) findViewById(R.id.customer);

        editTime = (EditText) findViewById(R.id.time);
        editDate = (EditText) findViewById(R.id.date);

        editDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) return;
                DatePickerDialog datePicker = new DatePickerDialog(AddEditAppointmentActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
                        selectedDateDay = arg3;
                        selectedDateMonth = arg2+1;
                        selectedDateYear = arg1;
                        editDate.setText(String.format("%s%d/%s%d/%d", selectedDateDay < 10 ? "0" : "", selectedDateDay, selectedDateMonth < 10 ? "0" : "", selectedDateMonth, selectedDateYear));

                    }
                }, selectedDateYear, selectedDateMonth - 1, selectedDateDay);
                datePicker.show();
            }
        });
        editTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) return;
                TimePickerDialog timePicker = new TimePickerDialog(AddEditAppointmentActivity.this, new TimePickerDialog.OnTimeSetListener() {

                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        selectedTimeHour = hourOfDay;
                        selectedTimeMin = minute;
                        editTime.setText(String.format("%s%d:%s%d", selectedTimeHour < 10 ? "0" : "", selectedTimeHour, selectedTimeMin < 10 ? "0" : "", selectedTimeMin));
                    }
                }, selectedTimeHour, selectedTimeMin, false);
                timePicker.show();
            }
        });

        editDuration = (EditText) findViewById(R.id.duration);
        editNotes = (EditText) findViewById(R.id.notes);

        editRepeat = (EditText) findViewById(R.id.repeat);

        //Trying to make keyboard not to auto-pop
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editRepeat.getWindowToken(),0);


        editRepeat.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) return;

                AlertDialog.Builder builder = new AlertDialog.Builder(AddEditAppointmentActivity.this);
                builder.setTitle("Make your selection");
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        editRepeat.setText(items[item]);
                    }
                });
                AlertDialog alert = builder.create();

                alert.show();


            }
        });



        String appointmentId = getIntent().getStringExtra("APPOINTMENT_ID");
        Long startTime = getIntent().getLongExtra("START_TIME", 0);

        DatabaseHelper mDbHelper = new DatabaseHelper(this);
        db = mDbHelper.getWritableDatabase();
        Calendar cal;

        if (appointmentId == null) {
            appointment = new ShowUpAppointmentMessage();
            cal = Calendar.getInstance(SimpleTimeZone.getTimeZone("Asia/Jerusalem"));
            cal.setTime(new Date());
            if (startTime!=0)
                cal.setTime(DateTimeUtil.fromTimestamp(startTime));
        }
        else {
            appointment = DatabaseHelper.getAppointment(db, appointmentId);
            editCustomer.setText(appointment.getCustomer().getName());
            selectedCustomer = appointment.getCustomer();
            cal = Calendar.getInstance(SimpleTimeZone.getTimeZone("Asia/Jerusalem"));
            cal.setTime(DateTimeUtil.fromTimestamp(appointment.getStartTime()));

            editDuration.setText(appointment.getDuration().toString());
            editNotes.setText(appointment.getNotes());
            editRepeat.setText(items[appointment.getRepeated().intValue()]);
        }

        selectedDateDay = cal.get(Calendar.DAY_OF_MONTH);
        selectedDateMonth = cal.get(Calendar.MONTH) + 1;
        selectedDateYear = cal.get(Calendar.YEAR);
        selectedTimeHour = cal.get(Calendar.HOUR_OF_DAY);
        selectedTimeMin = cal.get(Calendar.MINUTE);
        editDate.setText(String.format("%d/%d/%d", selectedDateDay, selectedDateMonth, selectedDateYear));
        editTime.setText(String.format("%s%d:%s%d", selectedTimeHour < 10 ? "0" : "", selectedTimeHour, selectedTimeMin < 10 ? "0" : "", selectedTimeMin));

        ArrayList<ShowUpCustomerMessage> customers = (ArrayList<ShowUpCustomerMessage>) DatabaseHelper.getCustomers(db);

        CustomersArrayAdapter customersArrayAdapter = new CustomersArrayAdapter(this, customers);
        editCustomer.setThreshold(0);
        editCustomer.setAdapter(customersArrayAdapter);
        editCustomer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectedCustomer = (ShowUpCustomerMessage)view.getTag();
            }
        });
    }


    public void onClickAddEditAppointment(View view) {
        if (selectedCustomer == null)
        {
            Toast.makeText(this, "Please select an existing client", Toast.LENGTH_LONG).show();
            return;
        }
        appointment.setCustomer(selectedCustomer);

        appointment.setTitle(selectedCustomer.getName());
        Calendar cal = Calendar.getInstance(SimpleTimeZone.getTimeZone("Asia/Jerusalem"));

        cal.set(selectedDateYear, selectedDateMonth - 1, selectedDateDay, selectedTimeHour, selectedTimeMin);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        appointment.setStartTime(cal.getTimeInMillis() / 1000L);
        appointment.setDuration(Long.parseLong(editDuration.getText().toString()));
        appointment.setNotes(editNotes.getText().toString());
        appointment.setRepeated((long)Arrays.asList(items).indexOf(editRepeat.getText().toString()));

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Updating appointment...");
        progressDialog.show();

        UpdateAppointmentTask updateAppointmentTask = new UpdateAppointmentTask(this, appointment) {
            @Override
            protected void onPostExecute(ShowUpAppointmentMessage editedAppointment) {
                if (editedAppointment != null) {
                    DatabaseHelper.addAppointment(db, editedAppointment);
                    Toast.makeText(AddEditAppointmentActivity.this, "Appointment updated!", Toast.LENGTH_LONG).show();
                    setResult(RESULT_OK, new Intent());
                    progressDialog.dismiss();
                    finish();
                }
                else {
                    Toast.makeText(AddEditAppointmentActivity.this, "Error updating", Toast.LENGTH_LONG).show();
                }
            }
        };
        updateAppointmentTask.execute((Void)null);

    }

}
